package com.service.impl;

import com.constant.AppConstant;
import com.entity.CarInfo;
import com.mapper.CarMapper;
import com.service.CarService;
import com.utils.TimeUtils;
import com.vo.CarVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author Yadasu
 * @date 2020/11/16 14:58
 */
@Service
public class CarServiceImpl implements CarService {
    @Autowired
    private CarMapper carMapper;

    /**
     * 新增
     *
     * @param carInfo
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer add(CarInfo carInfo) {
        return carMapper.addCarInfo(carInfo);
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public List<CarInfo> findAllCarInfo() {
        return carMapper.findAll();
    }

    /**
     * 按id指定查询
     *
     * @param carId
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public CarInfo findByCarId(Integer carId) {
        return carMapper.findById(carId);
    }

    /**
     * 取车时将费用一并更新
     *
     * @param carVo
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer getCar(CarVo carVo) {
        Integer id = carVo.getId();
        CarInfo byId = carMapper.findById(id);
        Date parkStart = byId.getPark_start();
        Date parkEnd = TimeUtils.getDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(carVo.getDate()));
        LocalDateTime start = TimeUtils.dateToLocalDateTime(parkStart);
        LocalDateTime end = TimeUtils.dateToLocalDateTime(parkEnd);
        Long hours = TimeUtils.getTheDifference(start, end);
        CarInfo carInfo1 = new CarInfo();
        carInfo1.setPark_money((int) (hours * AppConstant.PARKING_FEE));
        carInfo1.setPark_end(parkEnd);
        carInfo1.setId(id);
        return carMapper.updateCarInfo(carInfo1);

    }

    /**
     * 删除指定车辆
     *
     * @param carId
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer delCar(String carId) {
        return carMapper.delCarById(Integer.valueOf(carId));
    }


}
